package com.rivulet.fileserver.controller;

import com.rivulet.fileserver.pojo.FileData;
import com.rivulet.fileserver.service.FileService;
import com.rivulet.fileserver.tools.Results;
import com.rivulet.fileserver.tools.Tool;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@CrossOrigin
@RestController
public class FunctionController {
    @Value("${filepath}")
    private String fileDirPath;

    final private FileService fileService;

    public FunctionController(FileService fileService) {
        this.fileService = fileService;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file")MultipartFile multipartFile){
        String uuid= Tool.getUUID();
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
        Date now=new Date();
        String nowDay=format.format(now);
        File file=new File(fileDirPath+File.separator+nowDay+File.separator+uuid);
        File fileDir=new File(fileDirPath);
        try{
            if(!fileDir.exists()){
                fileDir.mkdir();
            }
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdir();
            }
            file.createNewFile();
            multipartFile.transferTo(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        /**
         * 获取源文件的各项元数据
         */
        FileData fileData=new FileData(
                uuid,
                multipartFile.getOriginalFilename(),
                multipartFile.getSize(),
                multipartFile.getContentType(),
                now,
                file.getAbsolutePath()
                );

        fileService.saveFileData(fileData);
        return uuid;
    }

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void downloadFile(HttpServletResponse response,@RequestParam("uuid")String uuid){
        /**
         * 首先根据uuid获取数据库中的文件元数据
         */
        Results<FileData> results=fileService.getFileData(uuid);
        /**
         * 若是获取元数据异常则抛出410异常
         */
        if(results.getCode()!=100){
           response.setStatus(410);
        }else {
            FileData fileData=results.getData();
            File file=new File(fileData.getFile_save_path());
            /**
             * 判断元数据中的文件原始路径是否存在该文件
             *
             */
            if(!file.exists()){
                response.setStatus(410);
                return;
            }
            /**
             * 下载功能的具体实现
             * 其中在文件输出时将文件名设为原始文件名
             */
            try{
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition",String.format("attachment;filename=\"%s\"", URLEncoder.encode(fileData.getFile_name(),"utf-8")));
                InputStream inputStream=new FileInputStream(file);
                IOUtils.copy(inputStream,response.getOutputStream());
                response.flushBuffer();
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/check",method = RequestMethod.GET)
    public FileData checkFile(@RequestParam("uuid")String uuid){
        /**
         * 首先根据uuid获取数据库中的文件元数据
         */
        Results<FileData> results=fileService.getFileData(uuid);
        return results.getData();
    }
}
